import { Button, message, Modal, Space, } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Access, getDvaApp, history, useAccess } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import { getImeiList, ImeiDelete } from '@/services/imei';
import { equipmentTypes, modelTypes, brandNames, mainBoardData, } from '@/utils/common';
import { getAgentList } from '@/services/agent';
import $utils from '@/utils/utils';

const ImeiList: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    // 获取权限
    const access = useAccess();
    const formRef = useRef<ProFormInstance>();
    const actionRef = useRef<ActionType>();
    const [initParams, setParams] = useState<any>();
    const [pageSize, setPageSize] = useState<number>(20);

    const [agentList, setAgentList] = useState<any>();

    const l_state: any = history.location.state;
    useEffect(() => {
        if (!initParams) {
            const data = {
                ...l_state,
            };
            setParams(data);
        }
    }, []);

    // 代理商列表
    useEffect(() => {
        const getAgentData = async () => {
            try {
                const msg = await getAgentList({ name: '', pageSize: 1000 });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.list.map((item: { id: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.id,
                        });
                    });
                    setAgentList(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
                message.error('代理商列表获取失败!');
            }
        };

        getAgentData();
    }, []);

    // 筛选重置时更新表单
    useEffect(() => {
        if (JSON.stringify(initParams) === '{}') {
            formRef && formRef.current?.resetFields();
            actionRef?.current?.reset && actionRef?.current?.reset();
        }
    }, [initParams]);

    const confirm = (id: number) => {
        Modal.confirm({
            title: '删除',
            content: '确定是否要删除',
            centered: true,
            maskClosable: true,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                // 删除imei
                const msg = await ImeiDelete({ id });
                if (msg.code === 0) {
                    actionRef && (actionRef?.current?.reload());
                }
            }
        });
    };

    const columns: ProColumns<any>[] = [
        {
            title: 'IMEI/柜体编号',
            dataIndex: 'keySearch',
            render: (text: any, record: any) => {
                const handleJump = () => {
                    const newTab = {
                        name: `查看IMEI${record.imei}`,
                        path: '/BasicConfig/IMEI/detail',
                        state: {
                            status: 'detail',
                            data: record
                        },
                    };
                    // 设置当前tab对象
                    $utils.setNewTab(dispatch, newTab);
                    $utils.addTab(dispatch, newTab)
                    history.push({
                        pathname: '/BasicConfig/IMEI/detail',
                        state: {
                            status: 'detail',
                            data: record
                        }
                    });
                };
                return (<div style={{ cursor: 'pointer' }} onClick={() => {
                    handleJump();
                }}>
                    {record.type === 3 ? (record.code || '--') : record.imei}
                </div>)
            },
        },
        {
            title: '设备类型',
            dataIndex: 'type',
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                options: equipmentTypes,
                placeholder: '全部'
            },
        },
        {
            title: '设备型号',
            dataIndex: 'model',
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                options: modelTypes,
                placeholder: '全部',
            },
            render: (text: any, record: any) => {
                return (<div>{record.model ? text : '--'}</div>)
            },
        },
        {
            title: '设备品牌',
            dataIndex: 'brand',
            hideInForm: true,
            valueType: 'select',
            fieldProps: {
                options: brandNames,
                placeholder: '全部',
            },
            width: '120px',
            render: (text: any, record: any) => {
                return (<div>{record.brand ? text : '--'}</div>)
            },
        },
        {
            title: '主板',
            dataIndex: 'mainboard',
            hideInForm: true,
            valueType: 'select',
            fieldProps: {
                options: mainBoardData,
                placeholder: '全部',
            },
            width: '120px',
            render: (text: any, record: any) => {
                return (<div>{(record.type === 3 && record.mainboard > 0) ? text : '--'}</div>)
            },
        },
        {
            title: '代理商名称',
            dataIndex: 'agentName',
            hideInForm: true,
            valueType: 'select',
            search: {
                transform: (value: any) => ({ agentId: value })
            },
            render: (text: any, record: any) => {
                return (<div>{record.agentName || '--'}</div>)
            },
            fieldProps: {
                options: agentList,
                showSearch: true,
            },
        },
        {
            title: '添加人',
            dataIndex: 'createUserName',
            search: false,
            hideInForm: true,
            width: '120px',
        },
        {
            title: '添加时间',
            dataIndex: 'createTime',
            search: false,
            hideInForm: true,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <Space key={record.id}>
                    <Access accessible={access.can_imeiAll.search}>
                        <Button type="primary" size="small" onClick={() => {
                            const newTab = {
                                name: `查看IMEI${record.imei}`,
                                path: '/BasicConfig/IMEI/detail',
                                state: {
                                    status: 'detail',
                                    data: record
                                },
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BasicConfig/IMEI/detail',
                                state: {
                                    status: 'detail',
                                    data: record
                                }
                            });
                        }}>详情</Button>
                    </Access>
                    {/* <Access accessible={access.can_imeiAll.search}>
                        <Button type="primary" size="small" onClick={() => {
                            const newTab = {
                                name: `编辑IMEI${record.imei}`,
                                path: '/BasicConfig/IMEI/detail',
                                state: {
                                    status: 'update',
                                    data: record
                                },
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BasicConfig/IMEI/detail',
                                state: {
                                    status: 'update',
                                    data: record
                                }
                            });
                        }}>编辑</Button>
                    </Access> */}
                    <Access accessible={access.can_imeiAll.delete}>
                        <Button type="primary" size="small" danger onClick={() => {
                            confirm(record.id)
                        }}>删除</Button>
                    </Access>

                </Space>
            ],
        },
    ];

    return (
        <PageContainer>
            {initParams && <ProTable<API.RuleListItem, API.PageParams>
                actionRef={actionRef}
                rowKey="id"
                pagination={{
                    pageSize: pageSize,
                    showSizeChanger: true,
                    size: 'small',
                    onShowSizeChange: (current, pageSize) => {
                        setPageSize(pageSize);
                    }
                }}
                form={{
                    initialValues: initParams
                }}
                formRef={formRef}
                search={access.can_imeiAll.search ? {
                    labelWidth: 120,
                    defaultCollapsed: false,
                    collapseRender: () => false,
                    span: {
                        xs: 24,
                        sm: 24,
                        md: 12,
                        lg: 12,
                        xl: 8,
                        xxl: 8,
                    },
                    optionRender: (searchConfig, formProps, dom) => [
                        dom.reverse()[0],
                        <Button
                            key="resetText"
                            onClick={() => {
                                setParams({});
                            }}
                        >
                            重置
                        </Button>,
                    ],
                } : false}
                beforeSearchSubmit={(params) => {
                    params.expressName && (params.expressId = params.expressName);
                    return params;
                }}
                options={false}
                title={() => [
                    <Access key="index" accessible={access.can_imeiAll.create}>
                        <Button type="primary" onClick={() => {
                            const newTab = {
                                name: `新建IMEI`,
                                path: '/BasicConfig/IMEI/detail',
                                state: {
                                    status: 'create'
                                }
                            };
                            // 设置当前tab对象
                            $utils.setNewTab(dispatch, newTab);
                            $utils.addTab(dispatch, newTab)
                            history.push({
                                pathname: '/BasicConfig/IMEI/detail',
                                state: {
                                    status: 'create'
                                }
                            });
                        }}>新建IMEI</Button>
                    </Access>

                ]}
                request={async (params) => {
                    const msg = await getImeiList(params);
                    if (msg.code === 0) {
                        // 将筛选条件存进 tabs
                        $utils.addTab(dispatch, {
                            name: 'IMEI管理',
                            path: '/BasicConfig/IMEI',
                            isTopMenu: true,
                            state: params
                        });
                    }
                    return {
                        data: msg.body?.list || [],
                        success: msg.code === 0,
                        total: msg.body?.count,
                    }
                }}
                columns={columns}
            />}
        </PageContainer >
    );
};

export default ImeiList;
